<template>
  <div class="navbar">
    <hamburger :is-active="sidebar.opened" class="hamburger-container" @toggleClick="toggleSideBar" />

    <breadcrumb class="breadcrumb-container" />

    <div class="right-menu">
      <el-dropdown class="avatar-container" trigger="click">
        <div class="avatar-wrapper">
          <span class="login_name">欢迎登陆 {{ uname }}</span>
          <i class="el-icon-caret-bottom" />
        </div>
        <el-dropdown-menu slot="dropdown" class="user-dropdown">
          <!--<el-dropdown-item>
            <span style="display:block;" @click="changePassword">修改密码</span>
          </el-dropdown-item>-->
          <el-dropdown-item>
            <span style="display:block;" @click="logout">退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <el-dialog
      :visible.sync="dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :modal-append-to-body="false"
      :before-close="handleClose"
      title="修改密码"
      center
    >
      <div class="form_reset">
        <el-form
          ref="form"
          :model="form"
          :rules="form_rules"
          label-width="120px"
          style="margin:10px;width:auto;"
        >

          <el-form-item prop="oldPwd" label="旧密码">
            <el-input
              v-model="form.oldPwd"
              :type="pwd.oldPwdType"
              auto-complete="off"
              placeholder="请输入旧密码"
            />
            <span class="show-pwd" @click="showPwd('old')">
              <svg-icon :icon-class="pwd.oldPwdType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-form-item prop="newPwd" label="输入密码">
            <el-input
              v-model="form.newPwd"
              :type="pwd.newPwdType"
              auto-complete="off"
              placeholder="请输入新密码"
            />
            <span class="show-pwd" @click="showPwd('new')">
              <svg-icon :icon-class="pwd.newPwdType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-form-item prop="checkPass" label="确认密码">
            <el-input
              v-model="form.checkPass"
              :type="pwd.checkPassType"
              auto-complete="off"
              placeholder="请再次输入密码"
            />
            <span class="show-pwd" @click="showPwd('check')">
              <svg-icon :icon-class="pwd.checkPassType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="onSubmitUser('form')">提 交</el-button>
      </span>

    </el-dialog>
  </div>

</template>

<script>
import { mapGetters } from 'vuex'
import Breadcrumb from '@/components/Breadcrumb'
import Hamburger from '@/components/Hamburger'
import { validatePass, validateNotNull } from '@/utils/validate'
import { changePwd } from '@/api/user'
import { getName } from '@/utils/auth'
export default {
  components: {
    Breadcrumb,
    Hamburger
  },
  data() {
    const validateOld = (rule, value, callback) => {
      if (value) {
        const str = value.replace(/^\s*|\s*$/g, '')
        if (value === '' || str === '') {
          callback(new Error('请输入旧密码！'))
        } else {
          if (value.length > 20) {
            callback(new Error('密码超出长度！'))
          } else {
            callback()
          }
        }
      } else {
        callback(new Error('请输入旧密码！'))
      }
    }
    const validatePwd = (rule, value, callback) => {
      // && this.dialog.option !== 'edit'
      if (validateNotNull(value)) {
        if (validatePass(value)) {
          callback()
        } else {
          callback(new Error('密码要包含大小写字母、数字和特殊符号，6~64位'))
        }
      } else {
        callback(new Error('不能为空！'))
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value) {
        const str = value.replace(/^\s*|\s*$/g, '')
        if (value === '' || str === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.form.newPwd) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请再次输入密码'))
      }
    }
    return {
      uname: '',
      pwd: {
        oldPwdType: 'password',
        checkPassType: 'password',
        newPwdType: 'password'
      },
      form: {

      },
      dialog: false,
      form_rules: {
        oldPwd: [
          { required: true, message: '旧密码不能为空！', trigger: 'blur' },
          { validator: validateOld, trigger: 'blur' }
        ],
        newPwd: [
          { required: true, message: '新密码不能为空！', trigger: 'blur' },
          { validator: validatePwd, trigger: 'blur' }
        ],
        checkPass: [
          { required: true, message: '不能为空！', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'name'
    ])
  },
  mounted() {
    /* console.log('=======================')
      console.log(this.name)*/

    this.uname = this.name ? this.name : getName()
  },
  methods: {
    handleClose() {
      this.dialog = false
      this.$refs['form'].clearValidate()
    },
    // 修改密码
    showPwd(msg) {
      switch (msg) {
        case 'old':
          if (this.pwd.oldPwdType === 'password') {
            this.pwd.oldPwdType = ''
          } else {
            this.pwd.oldPwdType = 'password'
          }
          break
        case 'new':
          if (this.pwd.newPwdType === 'password') {
            this.pwd.newPwdType = ''
          } else {
            this.pwd.newPwdType = 'password'
          }
          break
        case 'check':
          if (this.pwd.checkPassType === 'password') {
            this.pwd.checkPassType = ''
          } else {
            this.pwd.checkPassType = 'password'
          }
          break
      }
    },
    changePassword() {
      this.dialog = true
      this.form = {
        oldPwd: '',
        newPwd: '',
        checkPass: ''

      }
      this.pwd = {
        oldPwdType: 'password',
        checkPassType: 'password',
        newPwdType: 'password'
      }
    },
    onSubmitUser(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          // let uId = this.$store.state.user.uInfo.id
          const up = {
            oldPassword: this.form.oldPwd,
            newPassword: this.form.newPwd,
            verifyCode: ''
          }
          const code = localStorage.getItem('code')
          return new Promise((resolve, reject) => {
            changePwd(code, up).then(response => {
              // console.log(response)
              if (response.errorMsg === '成功') {
                this.$message({
                  message: '修改成功！',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: '修改失败',
                  type: 'error'
                })
              }
              this.dialog = false
              resolve()
            }).catch(error => {
              this.dialog = false
              reject(error)
            })
          })
        }
      })
    },
    toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    }
  }
}
</script>

<style lang="scss" scoped>
  .navbar {
    height: 50px;
    overflow: hidden;
    position: relative;
    background: #fff;
    box-shadow: 0 1px 4px rgba(0,21,41,.08);

    .hamburger-container {
      line-height: 46px;
      height: 100%;
      float: left;
      cursor: pointer;
      transition: background .3s;
      -webkit-tap-highlight-color:transparent;

      &:hover {
        background: rgba(0, 0, 0, .025)
      }
    }

    .breadcrumb-container {
      float: left;
    }

    .right-menu {
      float: right;
      height: 100%;
      line-height: 50px;

      &:focus {
        outline: none;
      }

      .right-menu-item {
        display: inline-block;
        padding: 0 8px;
        height: 100%;
        font-size: 18px;
        color: #5a5e66;
        vertical-align: text-bottom;

        &.hover-effect {
          cursor: pointer;
          transition: background .3s;

          &:hover {
            background: rgba(0, 0, 0, .025)
          }
        }
      }

      .avatar-container {
        margin-right: 30px;

        .avatar-wrapper {
          margin-top: 5px;
          position: relative;

          .user-avatar {
            cursor: pointer;
            width: 40px;
            height: 40px;
            border-radius: 10px;
          }

          .el-icon-caret-bottom {
            cursor: pointer;
            position: absolute;
            right: -20px;
            top: 25px;
            font-size: 12px;
          }
        }
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 4px;
      font-size: 16px;
      cursor: pointer;
      user-select: none;
    }
  }
</style>
